﻿using Common;
using NB.MGJ.Common;
using NB.MGJ.Common.API;
using NB.MGJ.Common.Utility;
using NB.MGJ.Model;
using NB.MGJ.Service;
using NB.MGJ.Service.CodeManage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace NB.MGJ.API
{
    [ApiAuthorizeFilter]
    [ApiHandleError]
    public class ApiMGJCodeManagerController : ApiBaseController<LogOnUserModel>
    {
        private CodeManageService _codeManageService;
        private ApplyCodeService acservive = new ApplyCodeService();
        private FleeGoodsService _flee;

        public ApiMGJCodeManagerController()
        {
            _codeManageService = new CodeManageService();
            _flee = new FleeGoodsService();
        }
        [Route("nbapi/codemanager/code/allot/getallotlist")]
        [HttpGet]
        public async Task<IHttpActionResult> CodeAllotList(string Psearch, int enterpriseId, int pageIndex = 1, int pageSize = 10)
        {
            #region MyRegion
            //PagerModel pm = new PagerModel();
            //pm.Page = pageIndex;
            //pm.PageSize = pageSize;
            ////查询语句判断

            //pm.StrCondition += "";
            ////if (LogOnUser.EnterpriseId != 1)
            ////{
            ////    pm.StrCondition += "  F_EnterpriseId= " + LogOnUser.EnterpriseId;
            ////}

            //if (Psearch != null)
            //{
            //    pm.StrCondition += " and T_EnterpriseName like '%" + Psearch + "%' ";
            //}
            //var result = _codeManageService.GetCurrentUserAllotCodePagedList(pm, enterpriseId); 
            #endregion

            var Result =await _codeManageService.GetCurrentUserAllotCodePagedList(pageIndex, pageSize, enterpriseId, null, null, Psearch);
            return ApiSuccess(Result.PageData);
        }

         [ApiVisitFilter("codeManager")]
        [Route("nbapi/codemanager/gencode/list")]
        [HttpGet]
        public IHttpActionResult GetGenCodeList(string Rsearch, int pageIndex = 1, int pageSize = 10)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            //查询语句判断

            pm.StrCondition += "  F.ViewDel=0  ";
            if (LogOnUser.EnterpriseId != 1)
            {
                pm.StrCondition += " and F.EnterpriseId= " + LogOnUser.EnterpriseId;
            }

            if (Rsearch != null)
            {
                pm.StrCondition += " and  F.EnterpriseName like '%" + Rsearch + "%' ";
            }


            var result = _codeManageService.GetGenCodePagedList(ref pm, Rsearch);

            return ApiSuccess(result.PageData);
        }


        [Route("nbapi/codemanager/gencode/update")]
        [HttpPut]
        public IHttpActionResult GenCodeUpdate([FromBody]GenCodeModel model)
        {
            if (model == null)
            {
                return ApiFail("当前无法执行该操作");
            }
            _codeManageService.GenCodeUpdate(model.GenCodeId,
                model.EnterpriseUse,
                model.Query_Result_Content,
                model.Query_Message_Content,
                model.ProductBrand,
                model.BatchId,
                model.ProductId,
                model.CustomerId);
            return ApiSuccess(true);
        }

        #region 码申请
        /// <summary>
        /// 获取当前机构的直接上级机构
        /// </summary>
        /// <param name="enterpriseId"></param>
        /// <returns></returns>
        [Route("nbapi/codemanager/code/apply/topenterparise")]
        [HttpGet]
        public IHttpActionResult GetNbenterparise(int enterpriseId)
        {
            return ApiSuccess(new ManagerService().GetDirectSuperior(enterpriseId));
        }
         [ApiVisitFilter("codeApply")]
        [Route("nbapi/codemanager/code/apply/getlist")]
        [HttpGet]
        public IHttpActionResult GetUserCodeApplyList(int enterpriseId)
        {
            return ApiSuccess(_codeManageService.GetUserCodeApplyList(enterpriseId));
        }

        [Route("nbapi/codemanager/code/apply/delete")]
        [HttpGet]
        public IHttpActionResult CodeApplyDelete(int Id, int userId)
        {
            _codeManageService.CodeApplyDelete(Id, userId);
            return ApiSuccess(true);
        }

        [Route("nbapi/codemanager/code/apply")]
        [HttpPost]
        public IHttpActionResult CodeApplyAdd([FromBody]L.EntityModel.CodeManage_Allot model)
        {
            if (model == null)
            {
                return ApiFail("当前无法执行该操作");
            }
            if (model.ProductId == 0)
            {
                model.AllotProductName = "";
            }
            model.ApplyDate = DateTime.Now;
            model.ApplyUserId = LogOnUser.UserID;
            model.T_EnterpriseId = LogOnUser.EnterpriseId;
            model.T_EnterpriseName = LogOnUser.EnterpriseName;
            model.HasVerifie = 0;
            model.SerialNum = Constant.MSQSerialNum;
            int result = acservive.AddApplyService(model);
            return ApiSuccess(result);
        }

        #endregion
        /// <summary>
        /// 计算整版数量
        /// </summary>
        [Route("nbapi/codemanager/code/allot/add/codenums")]
        [HttpGet]
        public IHttpActionResult GetWholeBatchCount(string batchNo)
        {
            return ApiSuccess(_codeManageService.GetWholeBatchCount(LogOnUser.ECode, batchNo));
        }

        #region 码分配

        [Route("nbapi/codemanager/code/allot/add")]
        [HttpPost]
        public IHttpActionResult CodeAllotAdd([FromBody]CodeManage_Allot model)
        {
            if (model == null)
            {
                return ApiFail("当前无法执行该操作");

            }
            model.F_EnterpriseId = LogOnUser.EnterpriseId;
            model.F_EnterpriseName = LogOnUser.EnterpriseName;
            model.ApplyUserId = LogOnUser.UserID;        //主动分配填写当前登录人ID
            model.ApplyUserName = LogOnUser.LoginName;   //主动分配填写当前登录人
            model.ApplyDate = DateTime.Now;              //主动分配填写当前时间
            model.ApplyReason = "主动分配";
            model.HasVerifie = 1;
            model.VerificationNotes = "主动分配，自动审核通过";
            model.SerialNum = Constant.MFPSerialNum;
            model.CodeFunc = "1,2";
            model.AllotDate = DateTime.Now;
            bool _result = _codeManageService.CodeAllotAdd(model);
            if (!_result)
            {
                return ApiFail("当前码包含已分配项目");
            }
            return ApiSuccess(true);
        }

        [Route("nbapi/codemanager/code/allot/codebatch/get")]
        [HttpGet]
        public IHttpActionResult GetGenCodeBatch(int enterpriseId, int allottype = 0)
        {
            return ApiSuccess(_codeManageService.GetGenCodeBatchList(enterpriseId, allottype));
        }
        #endregion

        #region 码关联列表

        /// <summary>
        /// 码关联列表
        /// </summary>
        [ApiVisitFilter("codeRelation")]
        [Route("nbapi/codemanager/code/relation/page/list")]
        [HttpGet]
        public IHttpActionResult GetCodeRelatePageList(int pageIndex = 1, int pageSize = 10)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            var pageList = new CodeRelateService().GetCodeRelatePageList(ref pm, LogOnUser, 0);
            return ApiSuccess(pageList.PageData);
        }


        [Route("nbapi/codemanager/code/relation")]
        [HttpPost]
        public IHttpActionResult CodeRelationAdd([FromBody]CodeManage_Allot model)
        {
            // 判断是否绑定产品或产品批次
            string[] arrCodes = model.ArrCode;
            if (arrCodes == null || arrCodes[0] == null) { return ApiSuccess("当前尚未扫码"); }
            string str = "";
            string code = "";

            for (int i = 0; i < arrCodes.Length; i++)
            {
                if (i == 0) code = arrCodes[i].Split(',')[0].Substring(0,AppConst.SubStrLen);
                str += arrCodes[i] + ",";
            }
            string tableName = "nbcodemain.antifake_digitcode" + code;
            bool _exist = _codeManageService.ExistUsingBatOrPro(str.TrimEnd(','), tableName);
            if (_exist)//不存在
            {
                //添加关联信息
                CodeManage_Allot allot = new CodeManage_Allot();
                allot.AllotType = 2;//手机关联
                allot.ApplyDate = DateTime.Now;
                allot.AllotBatchId = 0;
                allot.AllotBatch = "无";
                CodeRelateService _codeRelationService = new CodeRelateService();
                int i = _codeRelationService.AddRelation(model);
                if (i > 0)
                {
                    //添加明细
                    _codeRelationService.BatchAddAllotDetail(arrCodes, i);
                    //批量修改
                    if (model.Type == 1)
                    {
                        _codeManageService.BatchUpdateProOrBat(tableName, model.ProductId, 1, arrCodes);
                    }
                    if (model.Type == 2)
                    {
                        _codeManageService.BatchUpdateProOrBat(tableName, model.AllotBatchId.Value, 2, arrCodes);
                    }
                    return ApiSuccess(true);
                }
                else { return ApiSuccess("关联失败"); }
            }
            else { return ApiSuccess("当前码包含已分配项目"); }
        }


        #endregion
    }

    public class ConditionddddddModel
    {
        public string[] arrCode { get; set; }
    }
}

